package com.kira.scaffoldmvc.SnowFlake;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class DoubleIdChainUtil {

    //用Map模拟Redis分区存储双ID
    Map<Integer, List<String>> map = new ConcurrentHashMap<>();

    private AtomicInteger count = new AtomicInteger(0);

    public String createDoubleIdChain(){

        //生成主id
        long mainId = SnowflakeUtils.nextId();
        int secondaryId = count.incrementAndGet();
        return mainId + "_" + secondaryId;

    }

    //通过存入Map来模仿存入Redis
    //doubleIdChain 格式如 "1256892300152455168_42"
    public void pushRedis(String doubleIdChain){

        //判断这个Key属于哪个分区，并放入分区
        Integer count= Integer.parseInt(doubleIdChain.split("_")[1]);
        Integer partition = count / 10;
        //放入分区
        map.computeIfAbsent(partition, k -> new ArrayList<>())
                .add(doubleIdChain);

    }

    //遍历Map中的所有键值对
    public void checkMapWithEntrySet() {
        for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
            Integer partition = entry.getKey();
            List<String> idChains = entry.getValue();
            log.info("分区{}: 值:{}", partition, idChains);
        }
    }

}
